import java.io.File

import javafx.application.Application
import javafx.scene.image.Image
import javafx.stage.{Stage, WindowEvent}
import login.DesEncrypter
import mainInterface.MainInterface
import org.apache.commons.io.FileUtils
import org.zeroturnaround.zip.ZipUtil
import tool.Tool
import utils.{SoftFileLock, Utils}
import utils.Implicits._

/**
  * Created by yz on 2019/3/21
  */
object Main {

  def main(args: Array[String]): Unit = {
    Application.launch(classOf[Main], args: _*)
  }

  class Main extends Application {

    override def start(primaryStage: Stage): Unit = {
      check
      val is = Main.getClass.getClassLoader.getResourceAsStream("logo.png")
      primaryStage.getIcons.add(new Image(is))
      primaryStage.setTitle("LiveFibAS PC 肝纤维化数据处理软件")

      val file = Tool.licenceFile
      if (file.exists() && file.isFile) {
        val str = file.str
        val macs = Utils.getMacs
        val b = macs.exists { mac =>
          val encStr = DesEncrypter.encrypt(mac)
          str == encStr
        }
        if (b) {
          Tool.enterMain(primaryStage)
        } else {
          Tool.enterLogin(primaryStage)
        }
      } else {
        Tool.enterLogin(primaryStage)
      }

      primaryStage.setWidth(600)
      primaryStage.setHeight(430)

      primaryStage.resizableProperty().setValue(false)
      primaryStage.setOnCloseRequest((event: WindowEvent) => {
        Tool.exit
      })
      primaryStage.show()

    }

    def check={
      if (!SoftFileLock.isLocked) {
        Utils.showError("错误！", "你已经启动了一个程序!")
        System.exit(0)
      }
    }

    override def init(): Unit = {
      Tool.stopServer
      val dir = Tool.workSpace
//      val files = Array("bin/live_boost-1.0.zip", "bin/jre1.8.0_112.zip", "bin/R-3.6.0.zip")
//      unzip(files)
      val path = System.getProperty("java.library.path")
      val newPath = s"${Tool.nativePath.getAbsolutePath};${path}"
      System.setProperty("java.library.path", newPath)
    }


    def unzip(fileNames: Array[String]) = {
      fileNames.foreach { fileName =>
        val file = new File(fileName)
        val prefix = Utils.getPrefix(file)
        val dir = new File("bin", prefix)
        if (!dir.exists())
          ZipUtil.unpack(file, dir.getParentFile)
      }

    }

  }

}


